using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace Website
{
    public static class ViewUserControlExtensionMethods
    {
        private static readonly TimeSpan _year = new TimeSpan(365, 0, 0, 0);

        public static void SetAsCacheDependency(this ViewUserControl arg)
        {
            SetAsCacheDependency(arg, TimeSpan.Zero);
        }

        public static void SetAsCacheDependency(this ViewUserControl arg, TimeSpan expiry)
        {
            if (null == arg)
            {
                throw new ArgumentNullException("arg");
            }

            FileInfo file = new FileInfo(arg.Server.MapPath(arg.AppRelativeVirtualPath));
            if (null != file)
            {
                arg.Response.Cache.SetCacheability(HttpCacheability.Public);

                if (expiry > TimeSpan.Zero)
                {
                    arg.Response.Cache.SetExpires(DateTime.UtcNow.Add((expiry < _year) ? expiry : _year));
                }

                arg.Response.AddFileDependency(file.FullName);
                arg.Response.Cache.SetLastModifiedFromFileDependencies();
                arg.Response.Cache.SetETagFromFileDependencies();
            }
        }
    }
}